package com.czy.blog.service;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.transaction.Transactional;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import com.czy.blog.dao.UserDao;
import com.czy.blog.entity.Role;
import com.czy.blog.entity.User;
import com.czy.blog.vo.PageVo;

/**  用户管理服务层 */
@Service
@Transactional
public class UserService{
	@Autowired
	private UserDao userDao;
	@Autowired
	private RoleService roleService;

	public void save(User user) {
		userDao.save(user);
	}

	public UserDao getUserDao() {
		return userDao;
	}

	public void setUserDao(UserDao userDao) {
		this.userDao = userDao;
	}

	public List<User> findAll() {
		return (List<User>) this.userDao.findAll();
	}

	public User findById(String id) {
		return this.userDao.findOne(id);
	}
	
	public void update(User user)
	{
		userDao.save(user);
	}

	public void delete(List<String> ids)
	{
		Iterable<User> users = userDao.findAll(ids);
		userDao.delete(users);
	}

	public Page<User> findByUsernameLike(String username,PageVo pageVo)
	{
		int pageNo = pageVo.getPage() - 1;
		Pageable page = new PageRequest(pageNo < 0 ? 0 : pageNo,pageVo.getRows());
		Page<User> pageContent =  userDao.findAll(findByUsernameSpec(username),page);
		return pageContent;
	}

	public Specification<User> findByUsernameSpec(final String username){
		return new Specification<User>() {
			@Override
			public Predicate toPredicate(Root<User> root,CriteriaQuery<?> query, CriteriaBuilder cb) {
				List<Predicate> ps = new ArrayList<Predicate>();
				
				if(StringUtils.isNotBlank(username)){
					ps.add(cb.like(root.<String> get("username"), "%" + username + "%"));
				}
				return cb.and(ps.toArray(new Predicate[0]));
			}
		};
	}

	public void setRoles(String userId, List<String> roleIds)
	{
		User user = findById(userId);
		List<Role> roles = roleService.findByIds(roleIds);
		user.setRoles(new HashSet<Role>(roles));
	}
}
